package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func _json(ctx *gin.Context) {
	type userIndo struct {
		UserName string `json:"user"`
		Age      int    `json:"age"`
		Password string `json:"-"` //忽略转换为json
	}
	// json响应结构体
	//user1 := userIndo{
	//	"zhangsan",
	//	18,
	//	"123",
	//}
	//ctx.JSON(200, user1)

	// json响应map
	//user2 := map[string]string{
	//	"username": "lisi",
	//	"age":      "23",
	//}
	//ctx.JSON(200, user2)

	//直接响应json
	ctx.JSON(http.StatusOK, gin.H{
		"username": "wangwu",
		"age":      "23",
	})
}

func _xml(ctx *gin.Context) {
	ctx.XML(http.StatusOK, gin.H{
		"user": gin.H{"nikename": "法外狂徒", "realName": "张三"},
		"age":  20,
	})
}

func _yaml(ctx *gin.Context) {
	ctx.YAML(http.StatusOK, gin.H{
		"user": gin.H{"nikename": "悟空", "realName": "孙悟空"},
		"age":  2000,
	})
}

func _html(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "index.html", gin.H{"username": "小王"})
}

func _redirect(ctx *gin.Context) {
	ctx.Redirect(301, "https://weibo.com")
}
func main() {
	router := gin.Default()
	//加载模版目录下所有的文件
	router.LoadHTMLGlob("templates/*")
	//文件响应
	//在golang中没有相对文件路径，只有相对项目的路径
	router.StaticFS("/img", http.Dir("./static/img"))

	router.GET("/string", func(ctx *gin.Context) {
		ctx.String(http.StatusOK, "你好！")
	})
	router.GET("/json", _json)
	router.GET("/xml", _xml)
	router.GET("/yaml", _yaml)
	router.GET("/html", _html)
	router.GET("/sina", _redirect)
	router.Run(":8080")
}
